<template>
  <el-drawer
    :visible="backWashVisible"
    v-loading="loading"
    @close="cancel"
    :wrapperClosable="false"
  
    style="z-index: 2012"
    append-to-body
    size="60%"
  >
    <template v-if="detail">
      <div
        slot="title"
        style="font-size: 28px; font-weight: bold; color: #1a1a1a"
      >
        {{ detail.comeFrom == 1 ? "申请线下返洗" : "申请线上返洗" }}
      </div>
      <el-descriptions :column="1" style="padding: 0 20px">
        <el-descriptions-item label="门店名称">{{
          shopDetail.shopName || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{
          detail.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{
          detail.customPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="渠道">
          {{ orderComeFromMap[detail.comeFrom] }}
        </el-descriptions-item>

        <el-descriptions-item label="商品信息">
          <div>
            <div v-for="item in detail.orderGoodPoList">
              {{ productListMap[item.goodsId].name }}[{{
                productListMap[item.goodsId].price
              }}][{{ item.buyNum }}份]
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="商品总额">
          {{ detail.totalPrice.toFixed(2) }} （元）</el-descriptions-item
        >
        <el-descriptions-item label="订单折扣"
          >{{ detail.discountRatio }}%</el-descriptions-item
        >
        <el-descriptions-item label="订单金额"
          >{{ detail.orderPrice.toFixed(2) }}（元）</el-descriptions-item
        >
        <el-descriptions-item label="鞋子数量">
          {{ detail.shoeNum }} 双
        </el-descriptions-item>
      </el-descriptions>
      <el-form
        :model="formData"
        @submit.native.prevent="handleSubmit"
        ref="formData"
        label-width="100px"
        class="order-create-form"
      >
        <el-form-item
          label-width="0"
          class="hiden-label"
          prop="shoeIds"
          label="鞋子信息"
        >
          <TableTongji  v-if="backWashVisible" style="margin-right: 10px" :orderId="detail.id" :tableData="detail.shoePoList" :orderDetail="detail" :scene="scene" :multiple="true" @updateSelectedFn="selectdFn"></TableTongji>
        
        </el-form-item>

        <template v-if="detail.comeFrom === '1'">
          <el-form-item label="取鞋日期" prop="orderPrice">
            <el-date-picker
              v-model="formData.getShoeTime"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
        </template>

        <el-form-item prop="shopRemark" label="商家备注">
          <el-input
            type="textarea"
            placeholder="请输入商家备注"
            v-model="formData.shopRemark"
          ></el-input>
        </el-form-item>

        <template v-if="detail.comeFrom !== '1'">
          <el-form-item
            :rules="[{ required: true, message: '请选择预约时间' }]"
            label="预约时间"
            prop="reserveTime"
          >
            <el-date-picker
              v-model="formData.reserveTime"
              :picker-options="cpickerOptions"
              forMat="yyyy-MM-dd HH"
              type="datetime"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item
            label="物流渠道"
            :rules="[{ required: true, message: '请选择物流渠道' }]"
            prop="wuLiUType"
          >
            <el-select
              v-model="formData.wuLiUType"
              placeholder="请选择物流渠道"
            >
              <el-option
                v-for="item in logisticsCompanyList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="validateForm">提交</el-button>
        </el-form-item>
      </el-form>

      <el-dialog
        custom-class="order-create-dialog"
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="dialogVisible"
        width="30%"
        append-to-body
        style="background-color: rgba(0, 0, 0, 0.6); z-index: 2013"
      >
        <div style="text-align: center">
          <div>
            <i
              style="color: #67c23a; font-size: 50px"
              class="el-icon-success"
            />
          </div>
          <h1>订单提交成功</h1>
          <p>可前往“订单详情”查看订单水洗码详情，并打印水洗码。</p>
        </div>
        <div slot="footer" style="text-align: center">
          <el-button @click="toDetail">订单详情</el-button>
          <el-button type="primary" @click="printReceipt">打印小票</el-button>
        </div>
      </el-dialog>

      <PrintOrderReceipt
        :detail="printOrderReceiptObject.detail"
        :shopName="printOrderReceiptObject.shopName"
        :id="printOrderReceiptObject.id"
        :productListMap="productListMap"
        ref="PrintOrderReceipt"
      />
    </template>
  </el-drawer>
</template>

<script>
import { getOrderDetail, orderReturnWash } from "@/api/order/index";
import { getShopDetail } from "@/api/shop/index";
import { getBackWashNextHour } from "@/utils/tool";
import TableTongji from "../inStorage/components/TableTongji.vue";
import {
  orderComeFromMap,
  washTypeList,
  IMAGE_OSS_URL,
  logisticsCompany,
  logisticsCompanyList,
} from "@/config/index";
import { formatDateTime } from "@/utils/formate";
import PrintOrderReceipt from "@/components/PrintOrderReceipt/PrintOrderReceipt.vue";
import { TableColumn } from "element-ui";
export default {
  props: ["backWashVisible", "detailId", "productListMap"],
  components: {
    PrintOrderReceipt,
    TableTongji
  },
  data() {
    return {
      scene:"detail",
      selected:[],
      detail: false,
      loading: false,
      dialogVisible: false,
      formData: {
        wuLiUType: "1",
        reserveTime: "",
        shopRemark: "",
        shoeIds: "",
        getShoeTime: "",
      },

      shopDetail: {},
      washTypeList,
      orderComeFromMap,
      logisticsCompany,
      logisticsCompanyList,
      multipleSelection: [],

      newDetail: null,

      printOrderReceiptObject: {
        detail: "",
        shopName: "",
        id: "back-print",
      },

      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() <= Date.now();
        },
      },

      cpickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now();
        },
        selectableRange: `09:00:00 - 18:00:00`,
      },
    };
  },
  watch: {
    backWashVisible(val) {
      if (val === false) {
        this.detail = null;
        this.dialogVisible = false;
        this.formData = {
          wuLiUType: "1",
          reserveTime: "",
          shopRemark: "",
          shoeIds: "",
          getShoeTime: "",
        };
        this.$emit("close");
      } else {
        this.getDetail();
      }
    },
  },
  methods: {

    selectdFn(val){
    // console.info("子组件回调",val)
    this.selected=val
    },

    handleSubmit(event){
       event.preventDefault(); // 阻止默认提交行为
    },
    formatDateTime,
    getDetail() {
      this.loading = true;
      getOrderDetail(this.detailId)
        .then((res) => {
          res.data.shoePoList.forEach((item) => {
            item.picture = item.picture
              ? item.picture.split(",").map((key) => {
                return  {
                    url: IMAGE_OSS_URL + key,
                    status: "success",
                    data: key
                   }
                })
              : [];
          });
          this.detail = res.data;
          // console.info(this.detail.shoePoList)
          this.loading = false;
          this.formData.reserveTime = getBackWashNextHour();
          this.formData.wuLiUType = "1";
          this.getShopDetail(res.data.shopId);
        })
        .catch((err) => {
          // console.log(err);
          this.loading = false;
          this.$emit("close");
        });
    },
    getShopDetail(id) {
      getShopDetail(id).then((res) => {
        this.shopDetail = res.data;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.formData.shoeIds = val.map((item) => item.id).join(",");
    },
    toDetail() {
      this.$emit("toDetail", this.printOrderReceiptObject.detail.id);
    },
    printReceipt() {
      getOrderDetail(this.printOrderReceiptObject.detail.id).then((res) => {
        this.printOrderReceiptObject = {
          detail: res.data,
          shopName: this.$store.state.user.currentShop.shopName,
          id: "back-print",
        };
        this.$nextTick(() => {
          this.$refs.PrintOrderReceipt.$refs.printBtn.click();
        });
      });
    },
    cancel() {
      this.$emit("close");
    },
    validateForm() {
      
      let selectedShoe=this.selected.length
      if(selectedShoe==0){
        this.$message.error("请至少选择一双鞋子")
        return
      }

      this.$refs.formData.validate((valid) => { 
        if (valid) {
          let params = {};
          if (this.detail.comeFrom === "1") {
            params = {
              getShoeTime: this.formData.getShoeTime
                ? this.formData.getShoeTime.getTime()
                : "",
              orderId: this.detailId,
              shopRemark: this.formData.shopRemark,
              washIdLIst: this.selected.map(res=>{ return res.id}),
            };
          } else {
            params = {
              reserveTime: this.formData.reserveTime
                ? this.formData.reserveTime.getTime() / 1000
                : "",
              wuLiUType: this.formData.wuLiUType,
              orderId: this.detailId,
              shopRemark: this.formData.shopRemark,
              washIdLIst: this.selected.map(res=>{ return res.id}),
            };
          }
          
          orderReturnWash(params).then((res) => {
            this.printOrderReceiptObject.detail = res.data;
            this.dialogVisible = true;
          });
        }
      });
    },
  },
};
</script>

<style>
 .hiden-label .el-form-item__label{
  display: none !important;
}
</style>
